﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.BLL.Basic.Account;
using Gfw.BLL.Basic.ExceptionImpl;
using Gfw.BLL.Basic.User.Enums;
using Gfw.Models.Account;
using Gfw.Repositories.Account;
using Gfw.Repositories.Admin;
using Gfw.Repository;
using Gfw.Web.Models.User;

namespace Gfw.BLL.Basic.Facilities
{
    /// <summary>
    /// 充值（转账），客服转用户
    /// <para>用户转用户见Transfer类</para>
    /// </summary>
    public class RechargeFacility : IFacility
    {
        UserRechargeModel _recharge;

        #region 构造函数

        /// <summary>
        /// 构造函数初始化
        /// </summary>
        /// <param name="recharge"></param>
        public RechargeFacility(UserRechargeModel recharge)
        {
            if (recharge == null)
                throw new GfwVerifyException("充值的参数不正确！");

            var userRep = new UsrUserRepository();
            var user = userRep.Get(recharge.UserID);
            if (user == null)
                throw new Gfw.BLL.Basic.ExceptionImpl.GfwVerifyException("充值账户不存在！");

            if(recharge.RechargeMoney <= 0)
                throw new GfwVerifyException("充值的金额不正确！");

            this._recharge = recharge;
        }

        #endregion

        #region IFacility 成员

        /// <summary>
        /// 客户转会员
        /// </summary>
        /// <param name="unitOfWork"></param>
        public void Execute(UnitOfWork unitOfWork = null)
        {
            if(this._recharge == null)
                throw new GfwVerifyException("充值的参数不正确！");

            if (unitOfWork != null)
                throw new GfwException("当前事务只能作为原子事务，不允许与其它操作公用数据库事务。");

            UnitOfWork work = unitOfWork ?? new UnitOfWork();
            ActUserAccountinformationRepository userAccountRep = new ActUserAccountinformationRepository(); // 修改：用户账户信息表
            ActUserBargain4emoneyRepository emoneyRep = new ActUserBargain4emoneyRepository(); // 修改：用户电子币交易明细
            ActCompanyAccountinformationRepository comAccountRep = new ActCompanyAccountinformationRepository(); // 修改：公司帐户信息表
            ActCompanyRechargeRepository rechargeRep = new ActCompanyRechargeRepository(); // 修改：公司(用户)充值记录表
            ActCompanyBargainRepository bargainRep = new ActCompanyBargainRepository(); // 修改：公司帐户交易明细

            var userAccount = userAccountRep.Get(this._recharge.UserID, work);
            if (userAccount == null)
                throw new GfwVerifyException("充值用户不存在！");

            userAccount.ElectronicMoney += this._recharge.RechargeMoney;

            DateTime rechargeDate = DateTime.Now; // 时间要统一！
            ActUserBargain4emoney userEhistory = new ActUserBargain4emoney()
            {
                Id = Guid.NewGuid().ToString(),
                Userid = this._recharge.UserID,
                AwardSerialNo = "",
                Balance = userAccount.ElectronicMoney,
                Income = this._recharge.RechargeMoney,
                Outlay = 0,
                Taxation = 0,
                TaxationSerialNo = "",
                TradeAbstract = "充值",
                TradeType = (int)UserTradeTypeEnum.Recharge,
                TradeDate = rechargeDate,
                ToUserId = this._recharge.HandlerID,
                ToUserLoginName = "客服"
            };

            var comAccount = comAccountRep.GetAll(work).FirstOrDefault();
            if (comAccount == null)
            {
                comAccount = new ActCompanyAccountinformation()
                {
                    Id = Guid.NewGuid().ToString(),
                    SettlementDate = rechargeDate,
                };

                comAccountRep.Save(comAccount, work);
            }

            comAccount.Profit += this._recharge.RechargeMoney;
            comAccount.SettlementDate = rechargeDate;

            ActCompanyRecharge userRecharge = new ActCompanyRecharge()
            {
                Id = Guid.NewGuid().ToString(),
                Userid =  this._recharge.UserID,
                BankName = this._recharge.BankName,
                BankCardNo = this._recharge.BankCardNo,
                BankUserName = this._recharge.BankUserName,
                RechargeMoney = this._recharge.RechargeMoney,
                RechargeDate = rechargeDate,
                BankSerialNo = this._recharge.BankSerialNo,
                Handlerid = this._recharge.HandlerID,
                Status = this._recharge.Status,
            };

            ActCompanyBargain comBargain = new ActCompanyBargain()
            {
                Id = Guid.NewGuid().ToString(),
                Userid = this._recharge.UserID,
                TradeType = (int)UserTradeTypeEnum.Recharge,
                Income = this._recharge.RechargeMoney,
                Outlay = 0,
                Balance = comAccount.Profit,
                TradeDate = rechargeDate,
                TradeAbstract = "充值",
                AwardSerialNo = "",
                TaxationSerialNo = "",
            };


            userAccountRep.Update(userAccount, work);
            emoneyRep.Save(userEhistory, work);
            comAccountRep.Update(comAccount, work);
            rechargeRep.Save(userRecharge, work);
            bargainRep.Save(comBargain, work);


            if (unitOfWork == null)
                work.Commit();

            //如果用户没有激活，则需要激活用户
            //激活用户，没有做强制性认证
            if (userAccount.Status == (int)UserStatusEnum.NotActive
                && userAccount.ElectronicMoney >= 560)
            {
                ActiveUserFacility active = new ActiveUserFacility(userAccount.Userid);
                active.Execute();
            }
        }

        #endregion
    }
}
